import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAccountApi, logoutApi } from '@/api/login/index.ts'
import type { LoginAccountForm, UserLogin, UserInfo } from '@/api/login/types.ts'
import { getMemberApi } from '@/api/member/profile/index.ts'

// 定义 Store
export const useMemberStore = defineStore(
	'member',
	() => {
		// 会员信息
		const user = ref<UserLogin>({
			token: '',
			userId: '',
		})
		// 保存会员信息，登录成功时使用
		const userInfo = ref<UserInfo>()

		/* 账号登录 */
		function login(loginForm : LoginAccountForm) {
			return new Promise<void>((resolve, reject) => {
				loginAccountApi(loginForm).then((response: any) => {
					console.log(response)
					//保存用户ID和token
					user.value.userId = response.data.id
					user.value.token = response.data.token
					//执行获取用户信息的方法
					getUserInfo(response.data.id)
					resolve()
				}).catch((error) => {
					reject(error)
				})
			})
		}

		/*获取用户信息*/
		function getUserInfo(userId : string | number) {
			return new Promise<UserInfo>((resolve, reject) => {
				getMemberApi(userId)
					.then(({ data }) => {
						console.log(data)
						if (data) {
							userInfo.value = data;
							return resolve(data);
						}
					})
					.catch((error) => {
						reject(error);
					});
			});
		}

		/* 退出登录 */
		function logout() {
			return new Promise<void>((resolve, reject) => {
				logoutApi()
					.then(() => {
						clearProfile();
						resolve();
					})
					.catch((error) => {
						reject(error);
					});
			});
		}


		// 清理会员信息，退出时使用
		const clearProfile = () => {
			user.value.token = '';
			user.value.userId = '';
			userInfo.value = ({} as UserInfo)
		}

		// 记得 return
		return {
			user,
			getUserInfo,
			clearProfile,
			login,
			logout,
			userInfo
		}
	},
	// TODO: 网页持久化
	{
		// persist: true,
		persist: {
			// 调整为兼容多端的API
			storage: {
				getItem(key : any) {
					return uni.getStorageSync(key)
				},
				setItem(key : any, value : any) {
					uni.setStorageSync(key, value)
				}
			}
		}
	},
)